#!/bin/bash

# Delete temp and working files
rm realtimer.ttrace
rm result.csv
rm switchstats

# Iteration counter. This is not necessary and in a practical implementation
# will be omitted, but is here for data collection purposes
i=1

# Auxiliary variables to store cores to swap if they need to
maxMTTF=0
minMTTF=1000
maxMTTFcore=0
minMTTFcore=0
switch=0

# Voltage the processor operates. It is hardcoded, but could be fetched
# in the case of dynamic voltage systems

V=2

# Desired normalized MTTF
TARGETMTTF=2

while [ $i -le 600 ]
do
# Reads temperatures to feed to the Artificial Neural Network
    sensors | while read line
    do
	case "$line" in "Core "* )
		core=`echo $line | cut -c 6`
		temp=`echo $line | cut -c 10-11`
		let temp=$temp+273
		echo "std_block"$core $temp >> realtimer.ttrace
		# Generates temperature trace
		
		# Calculate the normalized MTTF using the Artificial Neural Network
		let MTTF=`echo "$temp $voltage" | ./neuralnetwork`
		
		# Order the maximum and minimum cores MTTF
		if [ `echo "$MTTF $maxMTTFcore" | ./isitgreater` -eq 1 ]; then
		    maxMTTFcore=$core
		    maxMTTF=$temp
		fi

		if [ `echo "$MTTF $minMTTFcore" | ./isitlesser` -eq 1 ]; then
		    minMTTFcore=$core
		    minMTTF=$temp
		fi
		switch=`echo "$MTTF $TARGETMTTF" | ./isitgreater`

	esac
    done

	# If we need to remap tasks because MTTF is low
    read lineswitch < switchstats
    switch=`echo $lineswitch | cut -c 5`
    if [ $switch -eq 1 ]; then
	echo "Acting"
	corelo=`echo $lineswitch | cut -c 1`
	corehi=`echo $lineswitch | cut -c 3`
	ps -aF | while read line
	do
	    linecore=`echo $line | cut -f7 -d" "`
	    changepid=`echo $line | cut -f2 -d" "`
	    process=`echo $line | cut -f11 -d" "`
	    if [ "$linecore" = "PSR" ]; then
		continue
	    fi
	    if [ $linecore -eq $corehi ]; then
		taskset -p -c $corelo $changepid
	    fi
	done
    fi
    
	# Set switch back to zero, as we've done all checks
    switch=0

    let i=$i+1
	
	# Step size between reliability checks and remaps
    sleep 1
	
done
